<template>
  <div class="common-container">
    <div class="portrait_container">
      <div class="portrait">
        <el-image :src="src" v-if="user.avatar == 1"></el-image>
        <el-image :src="src2" v-else-if="user.avatar == 2"></el-image>
        <el-image :src="src3" v-else-if="user.avatar == 3"></el-image>
        <el-image :src="src4" v-else-if="user.avatar == 4"></el-image>
        <el-image :src="src5" v-else-if="user.avatar == 5"></el-image>
        <el-image :src="src6" v-else-if="user.avatar == 6"></el-image>
        <el-image :src="portrait" v-else></el-image>
        <div class="xiugai">
          <span style="
                  cursor: pointer;
                  height: 100%;
                  display: flex;
                  align-items: center;
                " @click="editAvatar">修改</span>
        </div>
      </div>
      <div style="text-align: center;">
        <p>{{ user.userName }}</p>
        <p>
          {{ user.roleDescription }}
        </p>
      </div>
    </div>

    <div class="portrait_div">
      <div class="div_header">
        <div :style="activeName == 1 ? 'background:#7367f0;color: #fff;' : ''" @click="tabsClick(1)">基本信息</div>
        <div :style="activeName == 2 ? 'background:#7367f0;color: #fff;' : ''" @click="tabsClick(2)">修改密码</div>
        <div :style="activeName == 3 ? 'background:#7367f0;color: #fff;' : ''" @click="tabsClick(3)">登录日志</div>
      </div>

      <div class="div_box">
        <div class="outside-box" v-if="activeName == 1">
          <div class="box-container">
            <div class="line-two lineCommon">
              <p style="margin-right: 15px; width: 80px; text-align: right">
                用户名：
              </p>
              <p style="width: 200px; text-align: left">{{ user.userName }}</p>
            </div>

            <div class="line-four lineCommon">
              <p style="margin-right: 15px; width: 80px; text-align: right">
                角色：
              </p>
              <p style="width: 200px; text-align: left">
                {{ user.roleDescription }}
              </p>
            </div>

            <div class="line-four lineCommon" v-if="user.roleName == 'TENANT_ADMIN' || user.roleName == 'ORG_ADMIN' || user.roleName == 'INSTERALL_USER'">
              <p style="margin-right: 15px; width: 80px; text-align: right">
                租户：
              </p>
              <p style="width: 200px; text-align: left">{{ user.tenantName }}</p>
            </div>

            <div class="line-three lineCommon">
              <p style="margin-right: 15px; width: 80px; text-align: right">
                昵称：
              </p>
              <p style="width: 200px; text-align: left">
                {{ user.nickName
                }}<span @click="editnickName" style="
                        font-size: 14px;
                        margin-left: 8px;
                        color: #7367f0;
                        cursor: pointer;
                      ">修改</span>
              </p>
            </div>

            <div class="line-three lineCommon">
              <p style="margin-right: 15px; width: 80px; text-align: right">
                手机号：
              </p>
              <p style="
                      width: 200px;
                      text-align: left;
                      display: flex;
                      align-items: center;
                    ">
                {{ user.mobile }}
                <span @click="editmobile" style="
                        font-size: 14px;
                        margin-left: 8px;
                        color: #7367f0;
                        cursor: pointer;
                      ">修改</span>
              </p>
            </div>
          </div>
        </div>

        <div class="outside-box" v-else-if="activeName == 2">
          <div class="box-container">
            <el-alert type="error" style="margin-bottom: 20px; width: 500px">登录账号存在被盗风险，建议您定期更改密码，以确保账号安全
            </el-alert>
            <el-form :model="addForm" :rules="rules" ref="ruleForm" label-width="110px" class="demo-ruleForm">
              <el-form-item label="原密码：" prop="oldPwd" style="width: 410px">
                <el-input size="medium" class="input_240" autocomplete="off" type="password" show-password clearable
                  v-model="addForm.oldPwd" placeholder="输入原登录密码" readOnly @focus="onFocus" @blur="onBlur"
                  @input.native="onInput($event, addForm.oldPwd)" @mousedown.native="onMousedown"
                  maxlength="16"></el-input>
              </el-form-item>
              <el-form-item size="medium" label="新密码：" prop="pwd1" style="width: 410px">
                <el-input class="input_240" autocomplete="off" type="password" show-password clearable
                  v-model="addForm.pwd1" placeholder="输入新的登录密码" readOnly @focus="onFocus" @blur="onBlur"
                  @input.native="onInput($event, addForm.pwd1)" @mousedown.native="onMousedown"
                  maxlength="16"></el-input>
              </el-form-item>
              <el-form-item size="medium" label="确认密码：" prop="pwd2" style="width: 410px">
                <el-input class="input_240" autocomplete="off" type="password" show-password clearable
                  v-model="addForm.pwd2" placeholder="再次输入登录密码" readOnly @focus="onFocus" @blur="onBlur"
                  @input.native="onInput($event, addForm.pwd2)" @mousedown.native="onMousedown"
                  maxlength="16"></el-input>
              </el-form-item>

              <el-form-item style="width: 410px; text-align: right; margin-top: 50px">
                <el-button size="small" style="
                        padding: 10px 50px;
                        background: #655dcf;
                        color: #fff;
                        border: 1px solid #655dcf;
                        border-radius: 8px;
                        font-size: 16px;
                      " type="theme" @click="submitForm">保存
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <div class="outside-box" v-else-if="activeName == 3" style="padding: 10px 0 0 0;">
          <LoginLog ref="refLoginLog"></LoginLog>
        </div>

      </div>
    </div>

    <editMobile ref="refeditMobile"></editMobile>
    <editnickName ref="refeditnickName" :editRowInfo="editRowInfo"></editnickName>
    <editAvatar ref="refeditAvatar"></editAvatar>
  </div>
</template>

<script>
import tableStyleMixin from "@mixin/table-style";
import Pagination from "@components/Pagination.vue";
import Announcememt from "./components/announcement.vue";
import editMobile from "./components/editMobile.vue";
import editnickName from "./components/editnickName.vue";
import editAvatar from "./components/editAvatar.vue";
import LoginLog from "./components/LoginLog.vue";

import {
  reqUpdatePassword,
  reqHasSmsCode,
  reqChangeMobile,
  getSmsCode,
} from "@/api/api";
import { mapState, mapMutations } from "vuex";
import { validatePass } from "@utils/validate";

export default {
  name: "personal",
  components: {
    Pagination,
    Announcememt,
    editMobile,
    editnickName,
    editAvatar,
    LoginLog
  },
  data() {
    var checkPass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.addForm.pwd1) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      src: require("@assets/images/touxiang1.png"),
      src2: require("@assets/images/touxiang2.png"),
      src3: require("@assets/images/touxiang3.png"),
      src4: require("@assets/images/touxiang4.png"),
      src5: require("@assets/images/touxiang5.png"),
      src6: require("@assets/images/touxiang6.png"),
      bindForm: {
        mobile: "", //手机号
        code: "", //验证码
      },
      showCountDown2: true, //显示倒计时
      countDown2: "", //倒计时一分钟
      activeName: "1",
      pwdIconUrl: require("@assets/images/pwd_icon.png"),
      userIconUrl: require("@assets/images/user_icon.png"),
      tabPosition: "left",
      portrait: require("@assets/images/portrait.png"),
      addForm: {
        oldPwd: "",
        pwd1: "",
        pwd2: "",
      },
      rules: {
        oldPwd: [
          {
            required: true,
            message: "请输入原密码",
            trigger: "change",
          },
          {
            validator: validatePass,
            trigger: "change"
          },
        ],
        pwd1: [
          {
            required: true,
            message: "请输入新密码",
            trigger: "change",
          },
          {
            validator: validatePass,
            trigger: "change"
          },
        ],
        pwd2: [
          {
            required: true,
            message: "请再次输入新密码",
            trigger: "change",
          },
          {
            validator: checkPass,
            trigger: "change"
          },
        ],
      },
      value: true,
      page: 1,
      limit: 10,
      total: 10,
      editRowInfo: {},
    };
  },
  mixins: [tableStyleMixin],
  computed: {
    ...mapState([
      "nickname",
      "roleName",
      "mobile",
      "companyName",
      "user",
      "roleDescription",
      "username",
      "isExpire", //是否登录过期 lc
    ]),
    ...mapMutations(["saveMobile"]),
  },
  watch: {
    // 'user.avatar'(val) {
    //     console.log(val);
    // },
  },
  methods: {
    tabsClick(e) {
      this.activeName = e
    },
    // 修改头像
    editAvatar() {
      this.$refs.refeditAvatar.dialogVisible = true;
    },
    // 修改手机号弹窗
    editmobile() {
      this.$refs.refeditMobile.dialogVisible = true;
    },
    // 修改昵称弹窗
    editnickName() {
      this.editRowInfo = JSON.parse(
        JSON.stringify({
          nickname: this.user.nickName,
          id: this.user.userId,
        })
      );
      this.$refs.refeditnickName.dialogVisible = true;
    },
    // 更换手机号
    async onSubmit() {
      if (this.bindForm.mobile == "" || this.bindForm.mobile == null) {
        return this.$modal.notifyWarning("手机号不能为空");
      } else if (this.bindForm.code == "" || this.bindForm.code == null) {
        return this.$modal.notifyWarning("验证码不能为空");
      }
      //  更换手机号
      const res2 = await reqChangeMobile({
        id: this.user.userId,
        mobile: this.bindForm.mobile,
        code: this.bindForm.code,
      });
      if (res2.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("修改手机号成功");
      this.$store.commit("saveMobile", this.bindForm.mobile); //页面更换手机号
      this.closeEditMobile(); //取消按钮清空
    },
    // 取消
    closeEditMobile() {
      this.bindForm.mobile = ""; //清空手机号
      this.bindForm.code = ""; //清空验证码
      this.countDown2 = "";
    },
    // 点击获取短信验证码
    async smsCodeClick2() {
      this.$notify.closeAll();
      if (!this.bindForm.mobile)
        return this.$modal.notifyWarning("请输入手机号");
      if (this.bindForm.mobile.length < 11)
        return this.$modal.notifyWarning("手机号码为11位数字");
      if (!this.showCountDown2) return; //60s内只需发一次验证码
      // 验证手机号码是否存在
      // let res1 = await reqHasSmsCode({ mobile: this.bindForm.mobile });
      // if (res1.code !== 20000) return this.$modal.notifyWarning(res.message);
      // if (res1.data.count == 0)
      //   return this.$modal.notifyWarning("手机号码不存在，请输入正确的手机号");
      // 发送验证码
      let res = await getSmsCode({
        mobile: this.bindForm.mobile,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifyWarning("请注意查收手机短信验证码");

      this.showCountDown2 = false;
      this.countDown2 = 60;
      let intervalId = setInterval(() => {
        if (this.countDown2 > 0 && this.countDown2 <= 60) {
          this.countDown2--;
        } else {
          this.showCountDown2 = true;
          clearInterval(intervalId);
          intervalId = null;
        }
      }, 1000);
    },
    // 获取焦点
    onFocus(event) {
      setTimeout(function () {
        event.target.readOnly = false;
      }, 100);
    },
    // 失去焦点
    onBlur(event) {
      event.target.readOnly = true;
    },
    // 防止内容删完时出现账号和密码
    onInput(event, val) {
      if (val.length === 0) {
        this.onBlur(event);
        this.onFocus(event);
      }
    },
    // 防止多次点击时出现账号和密码
    onMousedown(event) {
      this.onBlur(event);
      this.onFocus(event);
    },
    // 修改密码
    async submitForm() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return;
        if (this.addForm.oldPwd == this.addForm.pwd1) return this.$modal.notifyWarning("原密码不允许与新密码相同");
        const res = await reqUpdatePassword({
          id: this.user.userId,
          oldPassWord: this.addForm.oldPwd,
          passWord: this.addForm.pwd1,
          verifyPassWord: this.addForm.pwd2,
        });
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        this.$modal.notifySuccess("密码修改成功，请重新登录");
        this.$refs.ruleForm.resetFields();
        sessionStorage.clear();
        setTimeout(() => {
          this.$router.push("/login");
          window.location.reload();
        }, 1000);
      });
    },

    // 登陆记录
    handleSizeChange() { },
    handleCurrentChange() { },
  },
  created() {
    // console.log(this.user,'user');
  },
};
</script>

<style scoped lang="less">
@import url("./personal.less");

// 短信验证码
.sms-code {
  // display: inline-block;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 37px;
  color: deepskyblue;
  border: 1px solid deepskyblue;
  border-radius: 3px;
  font-size: 13px;
  padding: 0px 10px;
  margin-left: 10px;
  cursor: pointer;
}

.code {
  position: absolute;
  width: 90px;
  height: 30px;
  line-height: 30px;
  top: 50%;
  transform: translateY(-50%);
  right: 0;
  color: #7367f0;
  cursor: pointer;

  // &:hover {
  //     // color: #556df4;
  //     color: #7978FA;
  // }
}

// ::v-deep .el-input--prefix .el-input__inner{
//   padding-left: 40px;
// }</style>
